//
//  WeiXinManager.m
//  6p
//
//  Created by weienjie on 15/3/3.
//  Copyright (c) 2015年 fenfen. All rights reserved.
//

#import "WeiXinManager.h"
//#import "CustomTools.h"
//#import "CommonHeader.h"
#import "LoginManager.h"


#define kOpenId         @"wx_openid"
#define kwxlogin        @"wxlogin"
#define kToken          @"wx_token"

@implementation WeiXinManager

+ (NSString *)openId
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:kOpenId];
}

+ (void)setOperId:(NSString *)openid
{
    [[NSUserDefaults standardUserDefaults] setObject:openid forKey:kOpenId];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (BOOL)wxlogin
{
     return [[NSUserDefaults standardUserDefaults] boolForKey:kwxlogin];
}

+ (void)setWxlogin:(BOOL)login
{
    [[NSUserDefaults standardUserDefaults] setBool:login forKey:kwxlogin];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

/**
 *  检测是否有安装微信客户端
 */
+ (BOOL)isWXAppInstalled
{
    return [WXApi isWXAppInstalled];
}

+ (void)weixinLogin
{
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kwxlogin];
    //重新授权
    //构造SendAuthReq结构体
    SendAuthReq* req =[[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo" ;
    req.state = @"123" ;
    //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendReq:req];
}


+ (void)weixinAutoLogin
{
//    [self refreshToken];
    NSDictionary *dict = @{@"sex":@"", @"nickname":@"", @"city":@"", @"headimgurl":@"", @"province":@""};
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSLog(@"json data:%@",json);
    NSString *token = [[NSUserDefaults standardUserDefaults] stringForKey:kToken] ? : @"";
    
    NSMutableDictionary *pra = [NSMutableDictionary dictionary];
    [pra setValue:@"weixin" forKey:@"type"];
    [pra setValue:self.openId forKey:@"openid"];
    [pra setValue:json forKey:@"info"];
    [pra setValue:token forKey:@"access_token"];
    [LoginManager loginWithData:pra type:LoginType_weixin];
}


+ (void)weixinLogout
{
    [self setOperId:nil];
    [self setWxlogin:NO];
}


+ (void)getAccess_tokenWithCode:(NSString *)code
{
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WX_AppID,WX_AppSecret,code];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSLog(@"dic = %@",dic);
                /*
                 {
                 "access_token" = "OezXcEiiBSKSxW0eoylIeJDUKD6z6dmr42JANLPjNN7Kaf3e4GZ2OncrCfiKnGWiusJMZwzQU8kXcnT1hNs_ykAFDfDEuNp6waj-bDdepEzooL_k1vb7EQzhP8plTbD0AgR8zCRi1It3eNS7yRyd5A";
                 "expires_in" = 7200;
                 openid = oyAaTjsDx7pl4Q42O3sDzDtA7gZs;
                 "refresh_token" = "OezXcEiiBSKSxW0eoylIeJDUKD6z6dmr42JANLPjNN7Kaf3e4GZ2OncrCfiKnGWi2ZzH_XfVVxZbmha9oSFnKAhFsS0iyARkXCa7zPu4MqVRdwyb8J16V8cWw7oNIff0l-5F-4-GJwD8MopmjHXKiA";
                 scope = "snsapi_userinfo,snsapi_base";
                 }
                 */
                NSString *access_token = [dic objectForKey:@"access_token"];
                if (access_token) {
                    [self getWX_userInfoWithAccessToken:access_token];
                }
                [self setOperId:[dic objectForKey:@"openid"]];
            }
        });
    });
}


+(void)getWX_userInfoWithAccessToken:(NSString *)token
{
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,self.openId];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSLog(@"dict = %@",dic);
                [[NSUserDefaults standardUserDefaults] setValue:token forKey:kToken];
                /*
                 {
                 city = Haidian;
                 country = CN;
                 headimgurl = "http://wx.qlogo.cn/mmopen/FrdAUicrPIibcpGzxuD0kjfnvc2klwzQ62a1brlWq1sjNfWREia6W8Cf8kNCbErowsSUcGSIltXTqrhQgPEibYakpl5EokGMibMPU/0";
                 language = "zh_CN";
                 nickname = "xxx";
                 openid = oyAaTjsDx7pl4xxxxxxx;
                 privilege =     (
                 );
                 province = Beijing;
                 sex = 1;
                 unionid = oyAaTjsxxxxxxQ42O3xxxxxxs;
                 }
                 */
                NSDictionary *dict = @{@"sex":[dic objectForKey:@"sex"], @"nickname":[dic objectForKey:@"nickname"], @"city":[dic objectForKey:@"city"], @"headimgurl":[dic objectForKey:@"headimgurl"], @"province":[dic objectForKey:@"province"]};
                NSError *error;
                NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
                NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                
                NSLog(@"json data:%@",json);
                
                NSMutableDictionary *pra = [NSMutableDictionary dictionaryWithDictionary:dic];
                [pra setValue:self.openId forKey:@"user_unique_id"];
                [pra setValue:token forKey:@"access_token"];
                [LoginManager loginWithData:pra type:LoginType_weixin];
            }
        });
        
    });
}
@end
